package com.javaeye.dengyin2000.gwtmodel.client.convert;

import pl.rmalinowski.gwtreflect.client.reflect.GWTRUtil;

public abstract class SimpleConverterAdapter implements IConverter {

	/**
	 * If class c is a string type (or more precise, assignable from
	 * {@link CharSequence}), this method will delegate type conversion to
	 * {@link #toString(Object)}. Otherwise, it will delegate type conversion
	 * to {@link #toObject(String)} using the object's {@link Object#toString()}
	 * value to convert it to a string first (or passing in null in case the
	 * value is null).
	 * 
	 * @see IConverter#convert(Object, Class)
	 */
	public Object convert(Object value, Class c) {
		if (c == String.class)
		{
			return toString(value);
		}
		else if (value instanceof CharSequence)
		{
			return toObject((value instanceof String) ? (String)value : value.toString());
		}
		else if (value != null && (GWTRUtil.getClass(c) != GWTRUtil.getClass(c)))
		{
			throw new IllegalArgumentException("unable to convert " + value + " to type " + c);
		}
		return value; // null
	}

	public abstract Object toObject(String string);
	public abstract String toString(Object value);

}
